package org.itli.jnsocket.Controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.itli.jnsocket.Pojo.Customer;
import org.itli.jnsocket.Result.Result;
import org.itli.jnsocket.Service.CustomerService;
import org.itli.jnsocket.Util.JWTUtil;
import org.itli.jnsocket.Util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@Tag(name = "客户接口")
@RequestMapping("/Customer")
@RestController
public class CustomerController {
    CustomerService service;

    JWTUtil jwt = new JWTUtil();

    @Autowired
    public void setService(CustomerService service) {
        this.service = service;
    }

    //查询所有客户
    @PostMapping("/AllCustoms")
    @Operation(summary = "查找全部客户")
    public Result<String> AllCustomers(@RequestBody PageUtil page) {
        String s = service.AllCustomers(page);
        return Result.success(s);
    }

    //新增客户
    @PostMapping("/AddCustomers")
    @Operation(summary = "添加客户")
    public Result<String> AddCustomer(@RequestHeader("Authorization") String token,@RequestBody Customer customer) {
        Map<String, Object> cliam;
        try{
            cliam = jwt.parseToken(token);
        } catch (Exception e) {
            return Result.success("令牌过期");
        }
        String username = (String) cliam.get("username");
        String s = service.AddCustomer(username, customer);
        return Result.success(s);
    }

    //修改客户
    @PostMapping("/AlterCustomers")
    @Operation(summary = "修改客户")
    public Result<String> AlterCustomer(@RequestHeader("Authorization") String token,@RequestBody Customer customer) {
        Map<String, Object> cliam;
        try{
            cliam = jwt.parseToken(token);
        } catch (Exception e) {
            return Result.success("令牌过期");
        }
        String username = (String) cliam.get("username");
        String s = service.AlertCustomer(username, customer);
        return Result.success(s);
    }

    //删除客户
    @PostMapping("/DeleteCustomers")
    @Operation(summary = "删除客户")
    public Result<String> DeleteCustomer(@RequestHeader("Authorization") String token,@RequestBody Customer customer) {
        Map<String, Object> cliam;
        try{
            cliam = jwt.parseToken(token);
        } catch (Exception e) {
            return Result.success("令牌过期");
        }
        String username = (String) cliam.get("username");
        String s = service.DeleteCustomer(username, customer);
        return Result.success(s);
    }
}
